package com.example.designmodel.bean;

import android.util.Log;
import android.widget.Toast;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * Created by sunsg on 16/8/24.
 */
public class CommentInvokeHandler implements InvocationHandler{
    private Object target;
    private Object proxy;

    public static <T> T getProxyInstance(Class<T> clazz){
        CommentInvokeHandler handler = new CommentInvokeHandler();
        try {
            T target = clazz.newInstance();
            handler.setTarget(target);
            Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),handler);
            handler.setProxy(proxy);
            Log.i("test","CommentInvokeHandler target.tostring = "+target.toString() +" proxy.tostring = "+proxy.toString());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) handler.getProxy();

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(target,args);
        String log = "_invoke method : " + method.getName()
                + " args : " + (null == args ? " null " : Arrays.asList(args).toString())
                + " result : " + result;
        Log.i("test", log);

        return result;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        return proxy;
    }

    public void setProxy(Object proxy) {
        this.proxy = proxy;
    }
}
